﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BSC;
using System.Web.Security;
using EmrDatastructure;
using EmrLogger;
using System.Data.Entity;

namespace EmrDAL
{
    public partial class EmrService : IEmrService
    {
        public virtual bool ValidateUser(string userName, string password)
        {
            try
            {
                Database.SetInitializer(new EmrContextInitializerIfNotExists());
                using (var context = new EmrContext())
                {
                    EmrUser e = context.Users.Find(userName);
                    if (e != null)
                    {
                        if (e.Password == password)
                        {
                            return true;
                        }
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error ValidateUser", ex);
                return false;
            }
        }

        public virtual MembershipCreateStatus CreateUser(string userName, string password, string email)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    EmrUser e = new EmrUser();
                    e.UserName = userName;
                    e.Password = password;
                    e.Email = email;
                    context.Users.Add(e);
                    context.SaveChanges(); 
                }
                return MembershipCreateStatus.Success;
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error CreateUser", ex);
                return MembershipCreateStatus.UserRejected;
            }
        }

        public virtual bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    EmrUser e = context.Users.Find(userName);
                    if (e != null)
                    {
                        if (e.Password != oldPassword)
                        {
                            return false;
                        }
                    }
                    e.Password = newPassword;
                    context.Entry(e).State = System.Data.EntityState.Modified;
                    context.SaveChanges(); 
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error ChangePassword", ex);
                return false;
            }
        }
    }
}
